//
//  LogView.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/12/10.
//

import SwiftUI
import Logging
import Swifter

struct LogView: View {
    @Environment(\.dismiss) var dismiss
    @State var content : String = ""
    let server = HttpServer()

    init() {
        let logger = Logger(label: "LogView")
        do {
            let content = try String(contentsOf: FileManagerHelper.getTodayLogFile(), encoding: String.Encoding.utf8)
            print("log content:\(content.count)")

            let lines = content.split(whereSeparator: \.isNewline).reversed()
            var newContent : String = ""
            lines.forEach { line in
                newContent.append("<p>\(line)</p>")
            }

            server["/"] = { request in
                return HttpResponse.ok(.htmlBody(newContent))
            }
            try server.start(8888,forceIPv4: true)

        } catch {
            logger.info("\(error)")
        }
    }

//    @FetchRequest(
//        sortDescriptors: [NSSortDescriptor(keyPath: \LoggerMessageEntity.createdAt, ascending: true)],
//        predicate: NSPredicate(format: "label == %@", "jiaozitaxi.iOS.app")
//    ) var messages: FetchedResults<LoggerMessageEntity>

    var body: some View {
//        List(messages, id: \.objectID) { message in
//            VStack(alignment: .leading) {
//                Text(timeFormatter.string(from: message.createdAt))
//                    .font(.footnote)
//                    .foregroundColor(.secondary)
//                Text(message.text)
//                    .lineLimit(2)
//            }
//        }
       // MainView()
        
        NavigationView {
            WebView(url:URL(string:"http://127.0.0.1:8888")!).environment(\.locale, Locale(identifier: ViewModel.shared.language.rawValue))
            Text("DeviceToken:\(ViewModel.shared.deviceToken)").padding()
                .onTapGesture {
                    UIPasteboard.general.string = ViewModel.shared.deviceToken
                }
        }.navigationBarBackButtonHidden(true) // 隐藏默认返回按钮
            .navigationBarItems(leading: backButton) // 添加自定义返回按钮
            .navigationTitle("http://\(NicHelper.getWifiIPAddress()):8888")
     
    }
    var backButton: some View {
        Button(action: {
            dismiss()
        }) {
            HStack {
                Image(systemName: "chevron.backward").foregroundColor(Color(hex: 0x333333))
            }
        }
    }
}

struct LogView_Previews: PreviewProvider {
    static var previews: some View {
        LogView()
    }
}
